package com.ltwc.lttv.adapter

import android.graphics.Color
import android.view.ContextThemeWrapper
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.leanback.widget.ImageCardView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ltwc.lttv.R
import com.ltwc.lttv.tools.Utils
import com.ltwc.lttv.listener.ItemListener
import com.ltwc.lttv.models.TVListViewModel
import com.ltwc.lttv.models.TVViewModel
import com.ltwc.lttv.tools.ScaleAnimationTool

/**
 * Description：
 * Created on 2024/1/29 18:42
 * Organization:华云
 * author：AHuangSHang
 **/
class OtherAdapter(private var tvListViewModel: TVListViewModel) :
    RecyclerView.Adapter<OtherAdapter.ViewHolder>() {

    private var listener: ItemListener? = null

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val view = itemView
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val cardView = object :
            ImageCardView(ContextThemeWrapper(parent.context, R.style.CustomImageCardTheme)) {}
        ScaleAnimationTool.startScaleAnimation(cardView, 1.0f, 0.9f, 1)
        val layoutParams = parent.layoutParams as ViewGroup.MarginLayoutParams
        layoutParams.topMargin = Utils.dpToPx(5F)
        cardView.layoutParams = layoutParams
        cardView.isFocusable = true
        cardView.isFocusableInTouchMode = true
        return ViewHolder(cardView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = tvListViewModel.getTVViewModel(position)
        val cardView = holder.view as ImageCardView
        val tvViewModel = item as TVViewModel
        cardView.titleText = tvViewModel.title.value
        cardView.tag = "item.videoUrl"
        Glide.with(holder.view.context).load(tvViewModel.logo.value).centerInside()
            .into(cardView.mainImageView)
        cardView.mainImageView.setBackgroundColor(Color.WHITE)
        cardView.setMainImageScaleType(ImageView.ScaleType.CENTER_INSIDE)
        cardView.contentText = "暂无内容"


        cardView.setOnFocusChangeListener { _, hasFocus ->
            listener?.onItemFocusChange(item, hasFocus)
            if (hasFocus) {
                ScaleAnimationTool.startScaleAnimation(cardView, 0.9f, 1.0f, 200)
            } else {
                ScaleAnimationTool.startScaleAnimation(cardView, 1.0f, 0.9f, 200)
            }
        }
        cardView.setOnClickListener { _ ->
            listener?.onItemClicked(item)
        }
    }

    override fun getItemCount() = tvListViewModel.size()

    fun setItemListener(listener: ItemListener) {
        this.listener = listener
    }
}